<template>
  <div class="content">
    <h3 style="margin: 0;padding: 10px 0 0;text-indent: 2em;">{{title}}
      <span class="right">
        <el-popover
          placement="bottom"
          title="提示"
          width="200"
          trigger="click">
          <p>未开始：该项处于创建状态；</p>
          <p>进行中：该项非创建和完成状态，且当前日期小于等于计划完成日期；</p>
          <p>完成：该项处于完成状态，且实际完成日期小于等于计划完成日期；</p>
          <p>延期完成：该项处于完成状态，且实际完成日期大于计划完成日期；</p>
          <p>延期未完成：该项非创建和完成状态，且实际完成日期大于计划完成日期。</p>
          <i class="el-icon-info" slot="reference"></i>
        </el-popover>
      </span>
    </h3>
    <div class="top">
      <div class="panelgroup">
        <div class="panelitem">
          <label>进度</label>
          <div class="panelbox">
            <count-to
              :start-val="0"
              :end-val="panels.percent"
              :duration="3000"
            ></count-to
            >% <br />
          </div>
        </div>
        <div class="panelitem">
          <label>延迟天数</label>
          <div :class="'panelbox'+(panels.delayDays>0?' panelbox-red':'')">
            <count-to
              :start-val="0"
              :end-val="panels.delayDays < 0 ? 0 : panels.delayDays"
              :duration="3000"
            ></count-to
            ><br />
          </div>
        </div>
        <div class="panelitem">
          <label>延期任务</label>
          <div :class="'panelbox'+(panels.delayTasks.length>0?' panelbox-red':'')"
            @click="handleClick({first:'panels',second:'delayTasks'})"
          >
            <count-to
              :start-val="0"
              :end-val="currentStage?panels.delayTasks.length/currentStage.allChildren.length*0.01:0"
              :duration="3000"
            ></count-to
            >%<br />
            <span style="font-size:12px;color:#F56C6C">{{panels.delayTasks?panels.delayTasks.filter(item=>item.iskeytask).length:0}}个关键</span>
          </div>
        </div>
        <div class="panelitem" v-for="item in rateofachieve" :key="item.name">
          <label>{{item.name}}</label>
          <div class="panelbox"
            @click="handleClick({first:'panels',second:'members',table:'team'})"
          >
            <count-to
              :start-val="0"
              :end-val="item.rate"
              :duration="3000"
            ></count-to
            >%<br />
            <span style="font-size:12px;color:#3f3f3f">节点达成率</span>
          </div>
        </div>
      </div>
      <div class="stageTasks" ref="stageTasks"></div>
    </div>
    <div class="piebarGroup">
      <pie-bar
        :title="'所有任务'"
        :name="'allTasks'"
        :dataList="allTasks"
        :rend="rend"
        @handleClick="handleClick"
      ></pie-bar>
      <pie-bar
        :title="'交付内容'"
        :name="'allTasks'"
        :dataList="delivers"
        :rend="rend"
        @handleClick="handleClick"
      ></pie-bar>
      <pie-bar
        :title="'关键任务'"
        :name="'allTasks'"
        :dataList="keyTasks"
        :rend="rend"
        @handleClick="handleClick"
      ></pie-bar>
    </div>
    <el-dialog
      ref="detailTable"
      :visible.sync="topen"
      width="50%"
      v-dialogDrag
      :close-on-click-modal="false"
    >
      <!-- <el-table stripe :data="tableData" :header-cell-style="{'background': '#96C0DE'}" :max-height="maxHeight">
        <template v-for="column in tableColumns">
          <el-table-column :label="column.name" :prop="column.prop" align="center">
            <template slot-scope="scope">
              <span v-if="['stateid','typeid','policyid'].includes(column.prop)">{{dataFormat(column.prop,scope.row[column.prop])}}</span>
              <span v-else>{{scope.row[column.prop]}}</span>
            </template>
          </el-table-column>
        </template>
      </el-table> -->
      <dynamic-table
        ref="dytable"
        :list="tableData"
        :options="options"
        :columns="tableColumns"
        :operates="operates"
        :diff="260"
      >
      </dynamic-table>
    </el-dialog>
  </div>
</template>

<script>
import CountTo from "vue-count-to";
import pieBar from "./pieBar.vue";
import echarts from "echarts";
import resize from "./mixins/resize";
import dynamicTable from "@/views/components/dynamicTable";
import { getDataList, getData, getTableCol } from "@/api/dynamic/dynamic";
var that;
export default {
  inject: ["app"],
  name: "report",
  mixins: [resize],
  components: {
    dynamicTable,
    CountTo,
    pieBar,
  },
  data() {
    return {
      chart: null,
      title: '',
      dataInfo: {},
      allData: [],
      listsById: null,
      listTree: null,
      newList: [],
      currentStage: null,
      rend: false,
      topen: false,
      panels: {
        percent: 90,
        delayDays: 0,
        delayTasks: [],
        members: [],
      },
      rateofachieve:[],
      stageTasks: {
        Unstart: [],
        Execute: [],
        Finished: [],
        Dfinished: [],
        Expired: [],
      },
      allTasks: {
        Unstart: [],
        Execute: [],
        Finished: [],
        Dfinished: [],
        Expired: [],
      },
      delivers: {
        Unstart: [],
        Execute: [],
        Finished: [],
        Dfinished: [],
        Expired: [],
      },
      keyTasks: {
        Unstart: [],
        Execute: [],
        Finished: [],
        Dfinished: [],
        Expired: [],
      },
      options: {
        // table 的参数
        stripe: true, // 是否为斑马纹 table
        loading: false, // 是否添加表格loading加载动画
        highlightCurrentRow: true, // 是否支持当前行高亮显示
        mutiSelect: false, // 是否支持列表项选中功能
      },
      operates: {
        // 列操作按钮
        width: 150,
        list: [],
      },
      tableData: [],
      tableColumns: [
        {
          name: "名称",
          prop: "name",
        },
        {
          name: "类型",
          prop: "typeid",
        },
        {
          name: "策略",
          prop: "policyid",
        },
        {
          name: "状态",
          prop: "stateid",
        },
        {
          name: "描述",
          prop: "description",
        },
        {
          name: "创建时间",
          prop: "createTime",
        },
        {
          name: "修改时间",
          prop: "modifyTime",
        },
      ],
    };
  },
  created() {
    // this.getTableColumns();
    this.getDataInfo();
    this.getList();
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
    that = this;
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  computed: {
    maxHeight() {
      return this.app.screenHeight - 300;
    },
  },
  methods: {
    initChart(flag = false) {
      this.chart = echarts.init(this.$refs.stageTasks);
      this.chart.setOption({
        tooltip: {},
        title: {
          text: "顶层任务",
          left: "center",
          top: 10,
        },
        legend: {
          data: ["未开始", "进行中", "完成", "延期完成", "延期未完成"],
          y: "bottom",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: '50px',
          containLabel: true,
        },
        xAxis: {
          minInterval: 1,
          type: "value",
        },
        yAxis: {
          show: false,
          type: "category",
          data: ["stageTasks"],
        },
        series: [
          {
            id: "Unstart",
            name: "未开始",
            type: "bar",
            stack: "total",
            itemStyle: {
              color: "#E6A23C",
            },
            label: {
              show: true,
            },
            emphasis: {
              focus: "series",
            },
            data: [this.stageTasks.Unstart.length],
          },
          {
            id: "Execute",
            name: "进行中",
            type: "bar",
            stack: "total",
            itemStyle: {
              color: "#67C23A",
            },
            label: {
              show: true,
            },
            emphasis: {
              focus: "series",
            },
            data: [this.stageTasks.Execute.length],
          },
          {
            id: "Finished",
            name: "完成",
            type: "bar",
            stack: "total",
            itemStyle: {
              color: "#409EFF",
            },
            label: {
              show: true,
            },
            emphasis: {
              focus: "series",
            },
            data: [this.stageTasks.Finished.length],
          },
          {
            id: "Dfinished",
            name: "延期完成",
            type: "bar",
            stack: "total",
            itemStyle: {
              color: "#9966ff",
            },
            label: {
              show: true,
            },
            emphasis: {
              focus: "series",
            },
            data: [this.stageTasks.Dfinished.length],
          },
          {
            id: "Expired",
            name: "延期未完成",
            type: "bar",
            stack: "total",
            itemStyle: {
              color: "#F56C6C",
            },
            label: {
              show: true,
            },
            emphasis: {
              focus: "series",
            },
            data: [this.stageTasks.Expired.length],
          }
        ],
      });
      if (flag) {
        this.chart.on("click", function (params) {
          return
          that.tableData = that[params.name][params.seriesId];
          that.topen = true;
          console.log(that.tableData)
        });
        this.rend = !this.rend;
      }
    },
    getDataInfo() {
      let type = this.$route.query.type;
      getData(type, this.$route.params.Id).then((response) => {
        if (response.code == 200) {
          this.dataInfo = response.data;
          this.panels.percent = this.dataInfo.percent;
        } else {
          this.$message.error(response.msg);
        }
      });
    },
    getList() {
      getDataList("/pmswbs/list", { projectid: this.$route.params.Id }).then(
        (response) => {
          this.allData = response.rows;
          this.updateData();
          this.initChart(true);
        }
      );
    },
    getTableColumns(table) {
      getTableCol({table}).then((response) => {
        this.tableColumns = response.data;
      });
    },
    MakeListTree(list, lists) {
      for (let current of lists) {
        if (current.parentid == list.id) {
          if (list.parents.length) {
            list.parents.forEach((parent) => current.parents.push(parent));
          }
          if (list.isroot !== true) {
            current.parents.push(list.id);
            current.parentid = list.id;
          }
          current = this.MakeListTree(current, lists);
          list.allChildren.push(current.id);
          list.children.push(current.id);
          current.allChildren.forEach((childId) =>
            list.allChildren.push(childId)
          );
        }
      }
      return list;
    },
    ResetListTree(lists) {
      const listById = {};
      var startLevel;
      for (let i in lists) {
        let current = lists[i];
        current.rowIndex = i;
        current.parentid =
          current.parentid == 0
            ? current.projectid
            : current.parentid;
        current.children = [];
        current.allChildren = [];
        current.parents = [];
        listById[current.id] = current;
      }
      return listById;
    },
    SortList2(parentList) {
      var newList = [];
      if (parentList.children && parentList.children.length > 0) {
        for (let li of parentList.children) {
          let item = this.listsById[li];
          newList.push(item);
          let appendList = this.SortList2(item);
          if (appendList.length > 0) {
            newList = newList.concat(appendList);
          }
        }
      }
      return newList;
    },
    updateData() {
      this.dataInfo.parents=[];
      this.dataInfo.children=[];
      this.dataInfo.allChildren=[];
      this.listsById = this.ResetListTree(this.allData);
      this.listTree = this.MakeListTree(this.dataInfo, this.allData);
      this.newList = this.SortList2(this.dataInfo);
      this.currentStage = this.listsById[this.dataInfo.children[0]]
      if(this.dataInfo.pharse){
        for(let id of this.dataInfo.children){
          if(this.listsById[id].name==this.dataInfo.pharse){
            this.currentStage = this.listsById[id];
            break;
          }
        }
      }
      this.title = this.currentStage.name
      this.panels.percent = this.currentStage.percent;
      this.panels.delayDays = this.currentStage.actual
        ? this.currentStage.actual-this.currentStage.estimated
        : parseInt(
            (new Date().getTime() -
              new Date(this.currentStage.esfinishdate).getTime()) /
              (1000 * 60 * 60 * 24)
          );
      for(let id of this.currentStage.allChildren){
        let item = this.listsById[id];
        let state = this.getStyle(item);
        if (state == "Expired" || state == "Dfinished") {
          this.panels.delayTasks.push(item);
        }
        if(this.currentStage.children.includes(item.id)){
          this.stageTasks[state].push(item);
        }
        if(item.iskeytask){
          this.keyTasks[state].push(item);
          let rate = item.actual?(2-item.actual/item.estimated)*0.01:0
          this.rateofachieve.push({name:item.name,rate,})
        }
        if(item.isneeddeliverable){
          this.delivers[state].push(item);
        }
        this.allTasks[state].push(item);
      }
      // this.panels.delayDays = this.dataInfo.acfinishdate
      //   ? parseInt(
      //       (new Date(this.dataInfo.acfinishdate).valueOf() -
      //         new Date(this.dataInfo.esfinishdate).valueOf()) /
      //         (1000 * 60 * 60 * 24)
      //     )
      //   : parseInt(
      //       (new Date().valueOf() -
      //         new Date(this.dataInfo.esfinishdate).valueOf()) /
      //         (1000 * 60 * 60 * 24)
      //     );
      // for (let item of this.allData) {
      //   let state = this.getStyle(item);
      //   let type = this.dataFormat("typeid", item.typeid);
      //   if (state == "Expired" || state == "Dfinished") {
      //     this.panels.delayTasks.push(item);
      //   }
      //   if (type == "里程碑") {
      //     this.panels.milestones.push(item);
      //   }
      //   if (type == "门") {
      //     this.panels.gates.push(item);
      //   }
      //   if (type == "阶段") {
      //     this.stageTasks[state].push(item);
      //   }
      //   this.allTasks[state].push(item);
      // }
    },
    getStyle(row) {
      let state = this.dataFormat("stateid", row.stateid);
      if (state == "创建") {
        return "Unstart";
      } else if (state == "完成") {
        if (
          row.acfinishdate &&
          parseInt(
              (new Date(this.dataInfo.acfinishdate).valueOf() -
                new Date(this.dataInfo.esfinishdate).valueOf()) /
                (1000 * 60 * 60 * 24)
            )<=0
        ) {
          return "Finished";
        } else {
          return "Dfinished";
        }
      } else {
        if (parseInt(
            (new Date().valueOf() -
              new Date(this.dataInfo.esfinishdate).valueOf()) /
              (1000 * 60 * 60 * 24)
          )>0) {
          return "Expired";
        } else {
          return "Execute";
        }
      }
    },
    handleClick(obj) {
      return false
      if(obj.table){
        this.getTableColumns(obj.table)
      }else{
        this.getTableColumns('project_wbs')
      }
      this.tableData = this[obj.first][obj.second];
      this.topen = true;
    },
  },
};
</script>
<style lang="scss" scoped>
.content {
  background: #eee;
  height: auto;
  box-sizing: border-box;
  padding: 10px 0;
  .top{
    display: flex;
    justify-content: center;
  }
  .panelgroup {
    width: 60%;
    height: 200px;
    padding: 50px 20px 10px;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    .panelitem {
      height: 100%;
      width: 120px;

      label {
        width: 100%;
        display: block;
        text-align: center;
        font-size: 16px;
        color: #999;
      }
      .panelbox {
        margin: 5% 6% 0;
        width: 90%;
        height: 80%;
        text-align: center;
        // line-height: 120px;
        padding: 50px 0 0;
        border-bottom: 5px solid #67c23a;
        box-sizing: border-box;
        border-radius: 10px;
        background: linear-gradient(
          rgba(255, 255, 255, 0.2) 5%,
          rgba(116, 202, 252, 0.5)
        );
      }
      .panelbox-red{
        border-color: #ff0000;
      }
    }
  }
  .stageTasks {
    width: 40%;
    height: 150px;
    top: 35px;
    // left: 66%;
  }
  .piebarGroup {
    width: 100%;
    height: auto;
    display: flex;
    margin-bottom: 60px;
    padding-top: 25px;
  }
}
.right{
  float: right;
  padding: 0;
  margin: 0;
}
</style>
